from time import sleep
import log
import bitbrowser_api as api
import asyncio
from pyppeteer import *

async def reupload_all(ws_link):
    sleep(0.2)

    log.Info(f"Browser list:{ws_link}")

    try:

        browser = await connect({'browserWSEndpoint': ws_link})
        page = await browser.newPage()
        await page.setViewport({'width': 1024, 'height': 768})
        
        log.Info(f"开始处理{ws_link}")
        log.Info(f"打开页面")
        # 打开Facebook Marketplace销售页面
        await page.goto('https://www.facebook.com/marketplace/you/dashboard', {
            'waitUntil': 'networkidle2',
            'timeout': 60000
        })
        
        # 等待页面加载完成
        await page.waitForSelector('body')

        # 等待并点击具有指定class的元素
        log.Info(f"点击待重新发布")
        opload_lable = await page.waitForXPath('//span[contains(text(), "待重新发布")]', timeout=10000)
        await opload_lable.click()
        await asyncio.sleep(1)
        log.Info("元素点击成功")

        # 获取所有"重新发布"按钮
        log.Info("查找所有重新发布按钮")
        reupload_buttons = await page.querySelectorAll('div[aria-label="重新发布"]')
        
        if len(reupload_buttons) > 0:
            log.Info(f"找到{len(reupload_buttons)}个重新发布按钮")
            # 跳过前三个重新发布按钮，从第四个开始点击
            for i in range(0, len(reupload_buttons)):
                try:
                    await reupload_buttons[i].click()
                    log.Info(f"成功点击第{i+1}个重新发布按钮")
                    await asyncio.sleep(2)  # 等待操作完成
                except Exception as e:
                    log.Error(f"点击第{i+1}个重新发布按钮失败: {str(e)}")
        else:
            log.Warning("未找到重新发布按钮")

        
        
        log.Info("点击完成")
        opload_lable = await page.waitForXPath('//span[contains(text(), "完成")]', timeout=10000)
        await opload_lable.click()
        await asyncio.sleep(1)

    except Exception as e:
        log.Error(f"Reupload failed:{ws_link}")
        log.Error(f"Error details:{e}")

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(reupload_all(api.get_pyppeteer_wslink_by_ids(api.get_alive_ids()[0])))
